package swu.myt;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AddNewUserServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 9138605154725450830L;
	
	public void init() {
		System.out.println("initialized!");
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String username = request.getParameter("name");
		String pass = request.getParameter("pass");
		String repass = request.getParameter("repass");
		String code = request.getParameter("code");//得到参数
		HttpSession session=request.getSession(true);//获取session,如果session不存在，就新建一个
		
		String validateCode = (String)session.getAttribute(MyFilter.LOGIN_VALIDATE_CODE);//得到验证码的真实值
		if(validateCode == null || !validateCode.equalsIgnoreCase(code)){//用户输入的验证码不存在或不匹配
			response.sendRedirect("/myapp/register/register.html");//回到原界面
			System.out.println("this is addnewuserServlet and validatecode not right!");
			return;
		}
		//到这里验证码验证成功，没成功不会继续下面的验证
		if(!pass.equals(repass)) {
			try(Writer writer = response.getWriter()){
				StringBuilder sb = new StringBuilder();
				sb.append("password not right");
				writer.write(sb.toString());
				writer.flush();
			}
			
		}
		if(username!=null&&pass!=null&&validateCode != null) {
			try {
				System.out.println(UserCheck.UserNotIn(username));
				if(UserCheck.UserNotIn(username)==true) {
					try {
						DBUtils.addUser(username,pass);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("addnewuserServlet input a new user.");
					response.sendRedirect("/myapp");
				}
				else {
					response.sendRedirect("/myapp/register/register.html");
					System.out.println("name have existed.");
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		
		}		
	}
	
	public void destory() {
		
		System.out.println("Servlet Destoried.");
	}
	
	


}
